/* $Id: bbsrf.c,v 1.2 2004/11/20 09:24:12 sby Exp $ */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/types.h>
#include <pwd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include "config.h"

#include <utmp.h>
#define U_FILE UTMP_FILE

#define UTMP_FILE _PATH_UTMP

#if MAXHOSTNAMELEN < UT_HOSTSIZE
	#define MAX_HOMENAME_LEN MAXHOSTNAMELEN
#else
	#define MAX_HOMENAME_LEN UT_HOSTSIZE
#endif

/* fill the hid with from hostname */
void gethid(char *hid, char *tty)
{
    int fd;
    char *tp;
    struct utmp data;

    gethostname(hid, MAX_HOMENAME_LEN);
    hid[MAX_HOMENAME_LEN] = '\0';
    tp = strrchr(tty, '/') + 1;
    if (tp && strlen(tp) == 5)
    {
	fd = open(U_FILE, O_RDONLY);
	if (fd < 0)
	    syslog(LOG_ERR, "%s: %m", U_FILE);
	else
	{
	    while (read(fd, &data, sizeof(data)) == sizeof(data))
		if (strcmp(data.ut_line, tp) == 0)
		{
		    if (data.ut_host[0]) {
			strncpy(hid, data.ut_host, MAX_HOMENAME_LEN);
			hid[MAX_HOMENAME_LEN] = '\0';
		    }
		    break;
		}
	    close(fd);
	}
    }
}

/*
   show ban file
   if filename exist, print it out, sleep 1 second, and return 0;
   otherwise, return -1.
 */
#ifdef BAN_FILE
int showbanfile(char *filename)
{
    FILE *fp;
    char buf[256];

    fp = fopen(filename, "r");
    if (fp)
    {
	while (fgets(buf, sizeof(buf), fp))
	    fputs(buf, stdout);
	printf("\n============================="
	       "=============================\n");
	fclose(fp);
	sleep(1);
    }
    return fp ? 0 : -1;
}
#endif

int main(void)
{
    int uid, rtv = 0;
    char *tty, ttybuf[32];
    char *fromhost, hidbuf[MAX_HOMENAME_LEN + 1];

    openlog("bbsrf", LOG_PID | LOG_PERROR, LOG_USER);
    chdir(BBSHOME);
    uid = getuid();

    while (1)
    {
#ifdef BAN_FILE
	if (!showbanfile(BAN_FILE))
	{
	    rtv = 1;
	    break;
	}
	else
#endif
	if (uid != BBSUID)
	{
	    syslog(LOG_ERR, "UID DOES NOT MATCH");
	    rtv = -1;
	    break;
	}
	else if (!getpwuid(uid))
	{
	    syslog(LOG_ERR, "YOU DONT EXIST");
	    rtv = -1;
	    break;
	}
	else if ((fromhost = getenv("SSH_CLIENT")) != NULL)
	{
	    *strchr(fromhost, ' ') = '\0';
	    tty = getenv("SSH_TTY");
	}
	else
	{
	    if ((tty = ttyname(0)) != NULL)
	    {
	        strcpy(ttybuf, tty);
	        gethid(hidbuf, ttybuf);
	    }
	    else
	    {
	        strcpy(ttybuf, "notty");
	        strcpy(hidbuf, "unknown");
	    }
	    tty = ttybuf;
	    fromhost = hidbuf;
	}
	execl(BBSPROG, "mbbsd", fromhost, tty, NULL);
	syslog(LOG_ERR, "execl(): %m");
	rtv = -1;
	break;
    }
    return rtv;
}
